package logic

import (
	"context"
	"errors"

	"github.com/myblogs/dao/mysql"
	"github.com/myblogs/models"
	md5p "github.com/myblogs/pkg/md5"
)

var (
	ErrorUserMsg     = errors.New("用户名已存在")
	ErrorUserNotMsg  = errors.New("用户名不存在")
	ErrorEmailMsg    = errors.New("邮箱已存在")
	ErrorEmailNotMsg = errors.New("邮箱不存在")
)

type UserLogic interface {
	Register(ctx context.Context, user *models.User) (*models.User, error)
	Login(ctx context.Context, loginReq models.LoginReq) (bool, error)
	GetUserName(ctx context.Context, username string) (int64, error)
}
type UserLogicImpl struct {
	UserDao mysql.UserDao
}

func NewUserLogic(userDao mysql.UserDao) *UserLogicImpl {
	return &UserLogicImpl{
		UserDao: userDao,
	}
}
func (u *UserLogicImpl) Register(ctx context.Context, user *models.User) (*models.User, error) {
	// 检查用户名是否存在
	exist, err := u.UserDao.CheckUserExist(ctx, user.UserName)
	if err != nil {
		return nil, err
	}
	if exist {
		return nil, ErrorUserMsg
	}
	// 检查邮箱是否存在
	exist, err = u.UserDao.CheckEmailExist(ctx, *user.Email)
	if err != nil {
		return nil, err
	}
	if exist {
		return nil, ErrorEmailMsg
	}
	if err := u.UserDao.Register(ctx, user); err != nil {
		return nil, err
	}
	return user, nil
}

func (u *UserLogicImpl) Login(ctx context.Context, loginReq models.LoginReq) (bool, error) {
	// 检查用户名是否存在
	if loginReq.Username != "" {
		exist, err := u.UserDao.CheckUserExist(ctx, loginReq.Username)
		if err != nil {
			return false, err
		}
		if !exist {
			return false, ErrorUserNotMsg
		}
	}
	// 检查邮箱是否存在
	if loginReq.Email != "" {
		exist, err := u.UserDao.CheckEmailExist(ctx, loginReq.Email)
		if err != nil {
			return false, err
		}
		if !exist {
			return false, ErrorEmailNotMsg
		}
	}

	psword := u.UserDao.Login(ctx, loginReq)

	return md5p.VerifyPassword(loginReq.Password, psword), nil
}
func (u *UserLogicImpl) GetUserName(ctx context.Context, username string) (int64, error) {
	return u.UserDao.GetUserName(ctx, username)
}
